package com.chalk.rabbitmq;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xiaoqiang
 * @Description
 * @date 2019/7/16 16:26
 */
@Service
public class MqSender implements RabbitTemplate.ConfirmCallback{
    private static Logger log = LoggerFactory.getLogger(MqSender.class);

    @Autowired
    private AmqpTemplate amqpTemplate;
    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MqSender(RabbitTemplate rabbitTemplate) {
        this.amqpTemplate = rabbitTemplate;
        //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 秒杀消息发送
     * @param message
     */
    public void sendMiaoshaMessage(Object message) {
        String msg = JSONUtil.toJsonStr(message);
        log.info("send message:"+msg);
        amqpTemplate.convertAndSend(RabbitMqConfig.MIAOSHA_QUEUE, msg);
    }

    public void send(Object message){
        String msg = JSONUtil.toJsonStr(message);
        log.info("send direct message = {}", msg);
        amqpTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE,RabbitMqConfig.ROUTING_KEY_A, msg);
    }

    public void sendTopic(Object message) {
        String msg = JSONUtil.toJsonStr(message);
        log.info("send topic message:{}", msg);
        amqpTemplate.convertAndSend(RabbitMqConfig.TOPIC_EXCHANGE, "topic.key1", msg+"1");
        amqpTemplate.convertAndSend(RabbitMqConfig.TOPIC_EXCHANGE, "topic.key2", msg+"2");
    }

    public void sendFanout(Object message) {
        String msg = JSONUtil.toJsonStr(message);
        log.info("send fanout message:{}", msg);
        amqpTemplate.convertAndSend(RabbitMqConfig.FANOUT_EXCHANGE, "", msg);
    }

    public void sendHeader(Object message) {
        String msg = JSONUtil.toJsonStr(message);
        log.info("send header message:{}",msg);
        MessageProperties properties = new MessageProperties();
        properties.setHeader("header1", "value1");
        properties.setHeader("header2", "value2");
        Message obj = new Message(msg.getBytes(), properties);
        amqpTemplate.convertAndSend(RabbitMqConfig.HEADERS_EXCHANGE, "", obj);
    }

    /**
     * 发送成功回调
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info(" 回调id:{}", correlationData);
        if (ack) {
            log.info("消息发送成功");
        } else {
            log.info("消息消费失败:{}", cause);
        }
    }
}
